// 管理后台首页函数

var constant = require('../../const');
var models = require('../../models');
var AV = require('leanengine')


/*
 * title: 登陆请求
 */
function postLogin(req, res) {
	var phoneNum = req.body.username;
	var password = req.body.password;

	console.log(phoneNum, password)
		// 判断用户是否是管理员
	var adminQuery = new AV.Query(models.MLAdminAdmin);

	adminQuery.include("role");
	var MLUser = models.MLUser;
	var userQuery = new AV.Query(MLUser);
	userQuery.equalTo("mobilePhoneNumber", phoneNum);
	adminQuery.matchesQuery("user", userQuery);

	var errorMsg = {
		"error": "账号或密码错误"
	};

	adminQuery.find({
		success: function(admins) {
			console.log(admins)
			if (0 == admins.length) {
				// 不是管理员
				res.redirect('/admin');
			} else {
				AV.User.logIn(phoneNum, password).then(function(user) {
					// 使用session保存nickname
					req.session.username = user.get('nickname');
					req.session.useravatar = user.get('avatar').url();
					console.log(req.session.username + " " + req.session.useravatar);
					//跳转到功能页面。
					res.redirect('/admin');
				}, function(error) {
					console.log(error)
						//登录失败，跳转到登录页面
					res.redirect('/admin');
				});
			}

		},
		error: function(error) {
			console.log(error)
				//res.redirect('/admin');
		}
	});

}

/*
 * title: 后台管理首页
 */
function getIndex(req, res) {
	// 判断用户是否已经登录
	if (req.AV.user) {
		console.log(0)
		res.render('admin/index', {
			"username": req.session.username,
			"avatar": req.session.useravatar
		});
	} else {
		console.log(1)
		res.render('admin/login');
	}
}

/*
 * title: 退出登陆请求
 */
function getLogout(req, res) {
	//avosExpressCookieSession将自动清除登录cookie信息
	AV.User.logOut();
	res.redirect('/admin');
}


/*
 * title: 查看用户资料
 */
function getUserInfo(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var userId = req.query.userId;
	var useryquery = new AV.Query(models.MLUser);
	useryquery.get(userId, {
		success: function(user) {
			var Galleryquery = new AV.Query(models.MLGallery);
			Galleryquery.include("belong_to")
			Galleryquery.include("images")
			Galleryquery.equalTo("belong_to", user)
			Galleryquery.find({
				success: function(results) {
					var voidquery = new AV.Query(models.MLVoice);
					voidquery.include("voice");
					voidquery.equalTo("belong_to", user);
					voidquery.find({
						success: function(voices) {

							if (voices.length > 0) {
								var data = {
									"username": req.session.username,
									"user": user,
									"gallery": results[0],
									"voice": voices[0]
								};
							} else {
								var data = {
									"username": req.session.username,
									"user": user,
									"gallery": results[0],
									"voice": null
								};
							};
							res.render('admin/userinfo', data);
						},
						error: function(error) {
							res.render({
								"code": 1,
								"msg": "error"
							});
						}
					})
				},
				error: function(error) {
					res.render({
						"code": 1,
						"msg": "error"
					});
				}
			})
		},
		error: function(error) {
			res.render({
				"code": 1,
				"msg": "error"
			});
		}
	})
}

/*
 * title: 系统消息页面
 */
function sysMsg(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var sendType = req.query.sendType || 0; //0:发给全部，1：只发给编辑推荐
	var data = {
		"sendType": sendType,
		"username": req.session.username
	}
	res.render('admin/sysMsg', data);
}

/*
 * title: 发送系统消息 post
 * 临时方法, 如果用户量很多最好不要用这种方式发, 否则肯定会出现超时错误(可考虑用广播消息)
 */
function sendSysMassMsg(req, res) {
	var content = req.body.content;
	var sendType = req.body.sendType;
	var title = req.body.title || "";
	var imgurl = req.body.imgurl || "";
	var useryquery = new AV.Query(models.MLUser);
	if (sendType == 1) {
		if (title != "" && imgurl != "") {
			AV.Push.send({
				channels: ["SweetMale", "SweetFemale"],
				data: {
					action: constant.NEW_SYSYTEM_MASS_PUSH,
					msg: content,
					title: title,
					url: imgurl,
					sound: "default"
				}
			});
		} else {
			AV.Push.send({
				channels: ["SweetMale", "SweetFemale"],
				data: {
					action: constant.NEW_SYSYTEM_MASS_PUSH,
					msg: content,
					title: "",
					url: "",
					sound: "default"
				}
			});
		}

		res.send({
			"code": 0,
			"msg": "发送成功"
		});
	} else {
		if (title != "" && imgurl != "") {
			AV.Push.send({
				channels: ["public"],
				data: {
					action: constant.NEW_SYSYTEM_MASS_PUSH,
					msg: content,
					title: title,
					url: imgurl,
					sound: "default"
				}
			});
		} else {
			AV.Push.send({
				channels: ["public"],
				data: {
					action: constant.NEW_SYSYTEM_MASS_PUSH,
					msg: content,
					title: "",
					url: "",
					sound: "default"
				}
			});
		}

		res.send({
			"code": 0,
			"msg": "发送成功"
		});
	}

}


/*
 * 临时创建管理员表
 */
function createAdmin(req, res) {
	var MLUser = models.MLUser;
	var userQuery = new AV.Query(MLUser);
	userQuery.get('5567ce93e4b046f4d983208d', {
		success: function(user) {
			console.log(user.id);
			var MLAdminRole = models.MLAdminRole;
			var roleQuery = new AV.Query(MLAdminRole);
			roleQuery.get('5566bed1e4b0663ab812042b', {
				success: function(role) {
					console.log(role.id);
					var MLAdmin = models.MLAdmin;
					var admin = new MLAdmin;
					admin.set('status', constant.ADMIN_STATUS_NORMAL);
					admin.set('user', user);
					admin.set('role', role);
					admin.setACL(new AV.ACL(AV.User.current()));
					admin.save();
					res.success("haha");
				},
				error: function(error) {}
			});
		},
		error: function(error) {}
	});
}

function jumpStore(req, res) {
	res.render('jump', null);
}


exports.postLogin = postLogin;
exports.getIndex = getIndex;
exports.getLogout = getLogout;
exports.getUserInfo = getUserInfo;
exports.sysMsg = sysMsg;
exports.sendSysMassMsg = sendSysMassMsg;
exports.createAdmin = createAdmin;
exports.jumpStore = jumpStore;